package com.sx.pipeline.ui.register

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnCancelListener
import com.lxj.xpopup.interfaces.OnConfirmListener
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.ui.register.adapter.SelectUnitNameAdapter
import com.sx.pipeline.ui.register.adapter.SelectUnitTypeAdapter
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IdentityType
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.app.config.RegisterType
import com.sx.pipeline.app.config.SmsCodeType
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.MyCityPickerListener
import com.sx.pipeline.custom.dialog.MyCityPickerPopup
import com.sx.pipeline.databinding.ActUnitRegisterBinding
import com.sx.pipeline.repos.http.res.AttributeList
import com.sx.pipeline.repos.http.res.ProvincesVO
import com.sx.pipeline.repos.http.res.UnitTypeVO
import com.sx.pipeline.utils.ItemDecorationUtils

/**
 * @Author: YY
 * @Date: 2022/4/14
 * @Description: 单位注册
 */
@Route(path = RoutePath.Register.REG_UNIT)
class UnitRegisterActivity: CYDataBindingBaseActivity<ActUnitRegisterBinding, RegisterVM>
    (R.layout.act_unit_register), View.OnClickListener {

    @Autowired(name = IntentKey.ID)
    @JvmField
    var identityID: Int? = 0

    // 是否可多选
    private var isMultiSelect: Boolean = false
    // 单位类型
    private lateinit var selectUnitTypeAdapter: SelectUnitTypeAdapter
    // 单位名称
    private lateinit var selectUnitNameAdapter: SelectUnitNameAdapter

    override fun initStatusBar() {
        ImmersionBar.with(this).statusBarDarkFont(true)
            .keyboardEnable(true).fitsSystemWindows(false).init()
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        super.initData()
        mBinding.setVariable(BR.onClick, this)

        // 注册类型和身份
        mViewModel.registerTypeField.set(RegisterType.UNIT_REGISTER.code)
        mViewModel.identityField.set(identityID)

        // 身份类型
        when(identityID) {
            IdentityType.OPERATING_UNIT.code -> {
                // 运营单位
                mBinding.tvRegisterTips.text = "${IdentityType.OPERATING_UNIT.flag}-${getString(R.string.txt_unit_reg)}"
                mBinding.tvEin.visibility = View.GONE
                mBinding.etEin.visibility = View.GONE
                isMultiSelect = false
            }
            IdentityType.BUILD_UNIT.code -> {
                // 施工单位
                mBinding.tvRegisterTips.text = "${IdentityType.BUILD_UNIT.flag}-${getString(R.string.txt_unit_reg)}"
                mBinding.tvUnitType.text = "经营类型(可多选)"
                isMultiSelect = true
            }
            IdentityType.SUPPLIER.code -> {
                // 供应商
                mBinding.tvRegisterTips.text = "${IdentityType.SUPPLIER.flag}-${getString(R.string.txt_unit_reg)}"
                mBinding.tvUnitType.text = "经营类型(可多选)"
                isMultiSelect = true
            }
        }

        // 获取单位类型和名称
        mViewModel.getUnitType(identityID)
    }

    override fun onPause() {
        super.onPause()
        mBinding.tvCountDown.stop()
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding.tvCountDown.stop()
    }

    override fun onClick(v: View) {
        when(v.id) {
            R.id.image_left_gray -> {
                // 返回
                finish()
            }
            R.id.tv_count_down -> {
                // 获取验证码
                val phone = mBinding.etPhone.text.toString()
                // 获取验证码
                mViewModel.sendSmsCode(phone, SmsCodeType.REGISTER_SMS.code)
            }
            R.id.sb_address -> {
                // 选择地址
                showProvincesDialog()
            }
            R.id.tv_privacy_agree -> {
                // 隐私协议
                mViewModel.getAgreement(1)
            }
            R.id.tv_user_agree -> {
                // 用户协议
                mViewModel.getAgreement(2)
            }
            R.id.tv_refresh -> {
                // 重新获取单位类型和名称
                mViewModel.getUnitType(identityID)
            }
            R.id.tv_register -> {
                // 注册
                register()
            }
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()

        // 验证码状态
        observe(mViewModel.smsCodeEvent) {
            mBinding.tvCountDown.start()
        }

        // 协议
        observe(mViewModel.agreementEvent) {
            RouteManager.Register.intentToAgreement(it!!)
        }

        // 单位类型
        setUnitTypeList()

        //注册成功
        observe(mViewModel.registerSuccessEvent){
            XPopup.Builder(this)
                .dismissOnTouchOutside(false)
                .isDestroyOnDismiss(true)
                .asConfirm(getString(R.string.hint),
                    getString(R.string.txt_register_success_tips),
                    getString(R.string.cancel),
                    getString(R.string.confirm),
                    {
                        ActivityUtils.finishActivity(SelectTypeIDRegActivity::class.java)
                        finish()
                    }, { }, true
                ).show()
        }
    }

    /**
     * 单位类型列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun setUnitTypeList() {

        mBinding.recyclerUnitType.addItemDecoration(
            ItemDecorationUtils(4, 6, 4, 6, 0))
        mBinding.recyclerUnitType.layoutManager = FlexboxLayoutManager(this,
            FlexDirection.ROW , FlexWrap.WRAP)

        // 单位类型
        observe(mViewModel.unitTypeListEvent) {
            if (it.isNullOrEmpty()) {
                mBinding.tvRefresh.visibility = View.VISIBLE
            } else {
                mBinding.tvRefresh.visibility = View.INVISIBLE

                // 单位类型id
                mViewModel.unitTypeIdsField.set(it[0].id.toString())
                // 单位类型名称
                mViewModel.unitTypeNameField.set(it[0].name)
                // 默认第一个选择
                it[0].isSelect = true

                if (!this::selectUnitTypeAdapter.isInitialized) {
                    selectUnitTypeAdapter = SelectUnitTypeAdapter(it as MutableList<UnitTypeVO>, isMultiSelect)
                }
                mBinding.recyclerUnitType.adapter = selectUnitTypeAdapter
                // item点击事件
                selectUnitTypeAdapter.setOnItemClickListener { adapter, _, position ->
                    if (isMultiSelect) {
                        var unitTypeIdsStr: String? = ""
                        var unitTypeName: String? = ""
                        // 多选
                        val unitTypeVO = adapter.data[position] as UnitTypeVO
                        unitTypeVO.isSelect = !unitTypeVO.isSelect
                        adapter.notifyItemChanged(position)

                        selectUnitTypeAdapter.data.forEach { data ->
                            if (data.isSelect) {
                                // 类型id
                                unitTypeIdsStr = "${data.id},$unitTypeIdsStr"
                                mViewModel.unitTypeIdsField.set(unitTypeIdsStr)
                                // 类型名称
                                unitTypeName = "${data.name},$unitTypeName"
                                mViewModel.unitTypeNameField.set(unitTypeName)
                            }
                        }

                    } else {
                        // 单选
                        selectUnitTypeAdapter.setSelectClickId(position)
                        val unitTypeVO = adapter.data[position] as UnitTypeVO
                        // 单位类型id
                        mViewModel.unitTypeIdsField.set(unitTypeVO.id.toString())
                        // 单位名称
                        mViewModel.unitTypeNameField.set(unitTypeVO.name)
                    }
                    // 选择单位名称
                    selectUnitName(it, position)
                }
                // 选择单位名称 默认0
                selectUnitName(it)
            }
        }
    }

    private fun selectUnitName(it: List<UnitTypeVO>, position: Int = 0) {
        mBinding.etUnitName.text!!.clear()
        // 单位名称-列表
        if (identityID == IdentityType.OPERATING_UNIT.code) {
            if (!TextUtils.isEmpty(it[position].attributeTitle)) {
                mBinding.tvSelectUnit.text = it[position].attributeTitle
            } else {
                mBinding.tvSelectUnit.text = "单位名称"
            }
            setUnitNameList(it, position)
        }
    }

    /**
     * 单位名称列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun setUnitNameList(it: List<UnitTypeVO>?, selectPosition: Int = 0) {
        if (!it!![selectPosition].attributeList.isNullOrEmpty()) {
            mBinding.recyclerUnitName.visibility = View.VISIBLE
            mBinding.etUnitName.visibility = View.GONE

            // 属性名称
            mViewModel.typeAttributeField.set(it[selectPosition].attributeList?.get(0)!!.attributeName)
            if (!this::selectUnitNameAdapter.isInitialized) {
                mBinding.recyclerUnitName.addItemDecoration(
                    ItemDecorationUtils(4, 6, 4, 6, 0))
                mBinding.recyclerUnitName.layoutManager = FlexboxLayoutManager(this,
                    FlexDirection.ROW , FlexWrap.WRAP)

                selectUnitNameAdapter = SelectUnitNameAdapter(it[selectPosition].attributeList as MutableList<AttributeList>)
                mBinding.recyclerUnitName.adapter = selectUnitNameAdapter
            }
            selectUnitNameAdapter.data = it[selectPosition].attributeList as MutableList<AttributeList>
            selectUnitNameAdapter.notifyDataSetChanged()
            // Item点击事件
            selectUnitNameAdapter.setOnItemClickListener { adapter, view, position ->
                selectUnitNameAdapter.setSelectClickId(position)
                // 属性名称
                mViewModel.typeAttributeField.set(it[selectPosition].attributeList?.get(position)!!.attributeName)
            }
        } else {
            mBinding.recyclerUnitName.visibility = View.GONE
            mBinding.etUnitName.visibility = View.VISIBLE
            mViewModel.typeAttributeField.set(null)
        }
    }


    /**
     * 省市区选择
     */
    private fun showProvincesDialog() {
        val popup = MyCityPickerPopup(ActivityUtils.getTopActivity(), true)
        popup.setCityPickerListener(object : MyCityPickerListener {
            override fun onCityConfirm(
                provincesVO: ProvincesVO?, cityVO: ProvincesVO?, areaVO: ProvincesVO?,
                province: String?, city: String?, area: String?, v: View?,
            ) {
                // 显示地址
                mBinding.sbAddress.setLeftTextColor(Color.parseColor("#666666"))
                mBinding.sbAddress.leftText = "$province $city $area"

                // 省市区id及详细地址
                mViewModel.provinceIDField.set(provincesVO!!.id.toInt())
                mViewModel.cityIDField.set(cityVO!!.id.toInt())
                mViewModel.areaIDField.set(areaVO!!.id.toInt())
                mViewModel.addressField.set("$province $city $area")
                if("全部".equals(area)){
                    mViewModel.locationId.set(cityVO!!.id.toInt())
                }else{
                    mViewModel.locationId.set(areaVO!!.id.toInt())
                }
            }

            override fun onCityChange(province: String?, city: String?, area: String?) {

            }
        })
        XPopup.Builder(this).asCustom(popup).show()
    }

    /**
     * 注册
     */
    private fun register() {
        val name = mBinding.etName.text.toString()
        val phone = mBinding.etPhone.text.toString()
        val smsCode = mBinding.etVerifyCode.text.toString()
        val identifier = mBinding.etEin.text.toString()
        val unitName = mBinding.etUnitName.text.toString()
        val isCheck = mBinding.toggleAgree.isChecked
        // 注册
        mViewModel.unitRegister(name, phone, smsCode, identifier, unitName, isCheck)
    }
}